package me.zhengjie.interceptor;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.util.BaseResponse;
import me.zhengjie.util.RedisUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器
 * @author Long
 * @date 2021/7/6 10:40
 */
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /*从请求头获取userToken*/
        String userToken = request.getHeader("userToken");
        if(StringUtils.isNotBlank(userToken)){
            log.info("userToken:"+userToken);
            String loginUserJSON = RedisUtils.INSTANCE.get(userToken);
            if(StringUtils.isNotBlank(loginUserJSON)){
                /*刷新用户登录时效60分钟*/
                RedisUtils.INSTANCE.set(userToken,loginUserJSON,3600);
                return true;
            }
            log.info("用户登录信息为空");

        }else {
            log.info("userToken为空");
        }
        response.setContentType("application/json;charset=utf-8");
        /*There is no user information for this login*/
        BaseResponse baseResponse = BaseResponse.failed("未登录，请先登录");
        String jsonString = JSON.toJSONString(baseResponse);
        response.getWriter().write(jsonString);
        response.getWriter().flush();
        return false;
    }
}
